/**
 * Copyright 2008 Frank van Lingen Licensed under the Apache License, Version
 * 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package superpodder.gui;


import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileOutputStream;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import superpodder.model.Settings;

public class SettingsView extends JDialog implements ActionListener {

    private static final long serialVersionUID = 2L;
    private final JTextField  downloadDir;
    private final JTextField  feeds;
    private final FileDialog  fileDialog;
    private final JTextField  history;
    private final JTextField  torrentExe;
    private final Choice      threads;
    private final Checkbox    torrentCheck;
    

    public SettingsView(JFrame parent) {
        super(parent, "Settings", true);
        System.out.println("Starting Settings Viewer");
        this.setMinimumSize(new Dimension(450, 250));
        this.setResizable(true);
        this.setSize(550, 270);

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                e.getWindow().setVisible(false);
            }
        });

        this.fileDialog = new FileDialog(this);

        // build the layout of this window
        final GridBagLayout gridbag = new GridBagLayout();
        final GridBagConstraints gbc = new GridBagConstraints();

        this.setLayout(gridbag);
        JLabel label;
        JButton button;
 
        // set external padding of components.
        gbc.insets = new Insets(2,2,2,2);
       
        gbc.weightx = 0;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        JLabel flabel = new JLabel("Select the Appropriate Values",
                SwingConstants.CENTER);
        gridbag.setConstraints(flabel, gbc);
        this.add(flabel);

        /*
         * Used to determine how to distribute space, which is important for
         * specifying resizing behavior. Unless you specify a weight for at
         * least one component in a row (weightx) and column (weighty), all the
         * components clump together in the center of their container. This is
         * because when the weight is zero (the default), the GridBagLayout
         * object puts any extra space between its grid of cells and the edges
         * of the container.
         */
        gbc.weightx = 0;
        /*
         * Specifies the number of cells in a row (for gridwidth) or column (for
         * gridheight) in the component's display area. The default value is 1.
         * Use GridBagConstraints.REMAINDER to specify that the component be the
         * last one in its row (for gridwidth) or column (for gridheight). Use
         * GridBagConstraints.RELATIVE to specify that the component be the next
         * to last one in its row (for gridwidth) or column (for gridheight).
         */

        gbc.gridwidth = 1;
        /*
         * Used when the component's display area is larger than the component's
         * requested size to determine whether (and how) to resize the
         * component. Possible values are GridBagConstraints.NONE (the default),
         * GridBagConstraints.HORIZONTAL (make the component wide enough to fill
         * its display area horizontally, but don't change its height),
         * GridBagConstraints.VERTICAL (make the component tall enough to fill
         * its display area vertically, but don't change its width), and
         * GridBagConstraints.BOTH (make the component fill its display area
         * entirely).
         */
        gbc.fill = GridBagConstraints.BOTH;
        button = new JButton("Set History");
        button.addActionListener(this);
        gridbag.setConstraints(button, gbc);
        this.add(button);

        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        this.history = new JTextField(40);
        this.history.setEditable(true);
        gridbag.setConstraints(this.history, gbc);
        this.add(this.history);

        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.BOTH;
        button = new JButton("Set Feeds");
        button.addActionListener(this);
        gridbag.setConstraints(button, gbc);
        this.add(button);

        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        this.feeds = new JTextField(40);
        this.feeds.setEditable(true);
        gridbag.setConstraints(this.feeds, gbc);
        this.add(this.feeds);

        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.BOTH;
        button = new JButton("Download Dir");
        button.addActionListener(this);
        gridbag.setConstraints(button, gbc);
        this.add(button);

        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        this.downloadDir = new JTextField(40);
        this.downloadDir.setEditable(true);
        gridbag.setConstraints(this.downloadDir, gbc);
        this.add(this.downloadDir);

        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        label = new JLabel("Parallel Downloads");
        gridbag.setConstraints(label, gbc);
        this.add(label);

        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        this.threads = new Choice();
        for (int i = 1; i < 21; i++) {
            this.threads.add(String.valueOf(i));
        }

        gridbag.setConstraints(this.threads, gbc);
        this.add(this.threads);
              

        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        flabel = new JLabel("");
        gridbag.setConstraints(flabel, gbc);
        this.add(flabel);
       
        
        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
        gridbag.setConstraints(separator, gbc);
        this.add(separator);
   
        gbc.weightx = 0;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        this.torrentCheck =new Checkbox("Activate Torrent Link", null, true);
        gridbag.setConstraints(this.torrentCheck, gbc);
        this.add(this.torrentCheck);    
        
        
        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        button = new JButton("Set Torrent");
        button.addActionListener(this);
        gridbag.setConstraints(button, gbc);
        this.add(button);

        gbc.weightx = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        this.torrentExe = new JTextField(40);
        this.torrentExe.setEditable(true);
        gridbag.setConstraints(this.torrentExe, gbc);
        this.add(this.torrentExe);


        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        flabel = new JLabel("", SwingConstants.CENTER);
        gridbag.setConstraints(flabel, gbc);
        this.add(flabel);

        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.LAST_LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        button = new JButton("Cancel");
        button.addActionListener(this);
        gridbag.setConstraints(button, gbc);
        this.add(button);

        gbc.weightx = 0;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.LAST_LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        button = new JButton("Save & Close");
        button.addActionListener(this);
        gridbag.setConstraints(button, gbc);
        this.add(button);

        this.feeds.setText(Settings.feeds);
        this.history.setText(Settings.history);
        this.downloadDir.setText(Settings.downloadDir);
        this.threads.select(String.valueOf(Settings.threads));
        this.torrentExe.setText(Settings.torrentExe);
        this.torrentCheck.setState(new Boolean(Settings.torrentLink));

    }

    public void actionPerformed(ActionEvent evt) {
        System.out.println("Event " + evt.getActionCommand());
        final String cmd = evt.getActionCommand();

        if (cmd.compareTo("Cancel") == 0) {
            this.setVisible(false);
        }
        if (cmd.compareTo("Save & Close") == 0) {
            Settings.history = this.history.getText();
            Settings.feeds = this.feeds.getText();
            Settings.downloadDir = this.downloadDir.getText();
            Settings.threads = new Integer(this.threads.getSelectedItem());
            Settings.torrentExe = this.torrentExe.getText();
            // FIXME: stupid hack otherwise it does not work.
            Boolean b = new Boolean(this.torrentCheck.getState());
            Settings.torrentLink = b.toString();
            this.saveAndClose();
            this.setVisible(false);
        }
        if (cmd.compareTo("Set Feeds") == 0) {
            this.fileDialog.setVisible(true);
            if (this.fileDialog.getDirectory() != null) {
                this.feeds.setText(this.fileDialog.getDirectory()
                        + this.fileDialog.getFile());
                this.fileDialog.setFile("");
                this.fileDialog.setDirectory("");
            }
        }
        if (cmd.compareTo("Set History") == 0) {
            this.fileDialog.setVisible(true);
            if (this.fileDialog.getDirectory() != null) {
                this.history.setText(this.fileDialog.getDirectory()
                        + this.fileDialog.getFile());
                this.fileDialog.setFile("");
                this.fileDialog.setDirectory("");
            }
        }
        if (cmd.compareTo("Download Dir") == 0) {
            this.fileDialog.setVisible(true);
            if (this.fileDialog.getDirectory() != null) {
                this.downloadDir.setText(this.fileDialog.getDirectory());
                // FIXME: a more elegant way of selecting a directory
                this.fileDialog.setFile("");
                this.fileDialog.setDirectory("");
            }
        }
        if (cmd.compareTo("Set Torrent") == 0) {
            this.fileDialog.setVisible(true);
            if (this.fileDialog.getDirectory() != null) {
                this.torrentExe.setText(this.fileDialog.getDirectory()
                        + this.fileDialog.getFile());
                this.fileDialog.setFile("");
                this.fileDialog.setDirectory("");
            }
        }

    }

    private void saveAndClose() {
        // get working directory
        final String path = System.getProperty("user.dir");
        // check for the properties file.
        final String configFile = path.concat("\\SuperPodder.cfg");
        try {

            final Properties properties = new Properties();
            properties.setProperty("history", Settings.history);
            properties.setProperty("feeds", Settings.feeds);
            properties.setProperty("download_dir", Settings.downloadDir);
            properties.setProperty("threads", String.valueOf(Settings.threads));
            properties.setProperty("torrentLink", Settings.torrentLink);
            properties.setProperty("torrentExe", Settings.torrentExe);
            final FileOutputStream fileIO = new FileOutputStream(configFile);
            properties.store(fileIO, "Parameters");
        } catch (final Exception e) {
            final String msg = new String("Unable to read " + configFile + ": "
                    + e.getMessage());
            JOptionPane.showMessageDialog(this, msg);
        }
    }
}
